<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>权限调试工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .card {
            background: white;
            padding: 20px;
            margin: 20px 0;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        h2 {
            color: #1890ff;
            margin-top: 0;
        }
        button {
            background: #1890ff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background: #40a9ff;
        }
        pre {
            background: #f0f0f0;
            padding: 15px;
            border-radius: 4px;
            overflow-x: auto;
        }
        .success {
            color: #52c41a;
        }
        .error {
            color: #ff4d4f;
        }
        .warning {
            color: #faad14;
        }
    </style>
</head>
<body>
    <div class="card">
        <h2>🔍 权限系统调试工具</h2>
        <p>这个工具可以帮助您检查当前的权限配置状态</p>
    </div>

    <div class="card">
        <h2>1️⃣ 当前 Token</h2>
        <div id="tokenInfo"></div>
        <button onclick="setAdmin()">设置为 Admin</button>
        <button onclick="setUser()">设置为 User</button>
        <button onclick="setGuest()">设置为 Guest</button>
        <button onclick="clearToken()">清除 Token</button>
    </div>

    <div class="card">
        <h2>2️⃣ 用户信息 API 测试</h2>
        <button onclick="testCurrentUser()">测试 /api/currentUser</button>
        <div id="userInfo"></div>
    </div>

    <div class="card">
        <h2>3️⃣ 权限路由 API 测试</h2>
        <button onclick="testRoutes()">测试 /api/routes/permission</button>
        <div id="routesInfo"></div>
    </div>

    <div class="card">
        <h2>4️⃣ 诊断建议</h2>
        <button onclick="diagnose()">运行诊断</button>
        <div id="diagnosis"></div>
    </div>

    <script>
        function setAdmin() {
            localStorage.setItem('token', 'mock_token_admin');
            showTokenInfo();
            alert('✅ 已设置为 Admin 用户，请点击"测试用户信息 API"按钮验证');
        }

        function setUser() {
            localStorage.setItem('token', 'mock_token_user');
            showTokenInfo();
            alert('✅ 已设置为普通用户，请点击"测试用户信息 API"按钮验证');
        }

        function setGuest() {
            localStorage.setItem('token', 'mock_token_guest');
            showTokenInfo();
            alert('✅ 已设置为访客用户，请点击"测试用户信息 API"按钮验证');
        }

        function clearToken() {
            localStorage.clear();
            showTokenInfo();
            alert('✅ 已清除所有缓存');
        }

        function showTokenInfo() {
            const token = localStorage.getItem('token');
            const html = `
                <pre>${token ? `Token: ${token}` : '<span class="warning">⚠️ 未设置 Token</span>'}</pre>
                ${token ? `<p class="success">✅ Token 格式正确</p>` : '<p class="error">❌ 请先设置 Token</p>'}
            `;
            document.getElementById('tokenInfo').innerHTML = html;
        }

        async function testCurrentUser() {
            const token = localStorage.getItem('token') || 'mock_token_admin';
            try {
                const response = await fetch('http://localhost:8002/api/currentUser', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                const data = await response.json();
                
                const hasPermissions = data.data && Array.isArray(data.data.permissions);
                const permissionCount = hasPermissions ? data.data.permissions.length : 0;
                
                const html = `
                    <pre>${JSON.stringify(data, null, 2)}</pre>
                    ${hasPermissions ? 
                        `<p class="success">✅ 用户信息包含 permissions 字段（${permissionCount} 个权限）</p>` : 
                        '<p class="error">❌ 用户信息缺少 permissions 字段！</p>'}
                `;
                document.getElementById('userInfo').innerHTML = html;
            } catch (error) {
                document.getElementById('userInfo').innerHTML = `
                    <p class="error">❌ 请求失败: ${error.message}</p>
                    <p class="warning">⚠️ 请确保开发服务器正在运行（npm start）</p>
                `;
            }
        }

        async function testRoutes() {
            const token = localStorage.getItem('token') || 'mock_token_admin';
            try {
                const response = await fetch('http://localhost:8002/api/routes/permission', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                const data = await response.json();
                
                const routeCount = data.data ? data.data.length : 0;
                
                const html = `
                    <pre>${JSON.stringify(data, null, 2)}</pre>
                    ${routeCount > 0 ? 
                        `<p class="success">✅ 成功获取 ${routeCount} 个路由配置</p>` : 
                        '<p class="error">❌ 路由数据为空！</p>'}
                `;
                document.getElementById('routesInfo').innerHTML = html;
            } catch (error) {
                document.getElementById('routesInfo').innerHTML = `
                    <p class="error">❌ 请求失败: ${error.message}</p>
                    <p class="warning">⚠️ 请确保开发服务器正在运行（npm start）</p>
                `;
            }
        }

        async function diagnose() {
            const token = localStorage.getItem('token');
            let issues = [];
            let fixes = [];

            // 检查1: Token 是否存在
            if (!token) {
                issues.push('❌ 未设置 Token');
                fixes.push('点击"设置为 Admin"按钮');
            } else {
                issues.push('✅ Token 已设置');
            }

            // 检查2: 测试 API
            try {
                const response = await fetch('http://localhost:8002/api/currentUser', {
                    headers: {
                        'Authorization': `Bearer ${token || 'mock_token_admin'}`
                    }
                });
                const data = await response.json();
                
                if (data.data && Array.isArray(data.data.permissions)) {
                    issues.push(`✅ 用户 API 返回 permissions 字段（${data.data.permissions.length} 个权限）`);
                } else {
                    issues.push('❌ 用户 API 未返回 permissions 字段');
                    fixes.push('检查 src/app.tsx 的 fetchUserInfo 函数是否使用了 Mock API');
                }
            } catch (error) {
                issues.push('❌ 无法连接到开发服务器');
                fixes.push('运行 npm start 启动开发服务器');
            }

            // 生成诊断报告
            const html = `
                <h3>诊断结果</h3>
                ${issues.map(issue => `<p>${issue}</p>`).join('')}
                ${fixes.length > 0 ? `
                    <h3 class="warning">需要修复的问题</h3>
                    ${fixes.map(fix => `<p>🔧 ${fix}</p>`).join('')}
                ` : '<p class="success">✅ 所有检查通过！</p>'}
                <h3>下一步操作</h3>
                <ol>
                    <li>确保设置了正确的 Token</li>
                    <li>点击"测试用户信息 API"验证数据</li>
                    <li>刷新主应用页面（http://localhost:8002）</li>
                    <li>打开浏览器控制台查看日志</li>
                </ol>
            `;
            document.getElementById('diagnosis').innerHTML = html;
        }

        // 页面加载时显示当前状态
        window.onload = function() {
            showTokenInfo();
        };
    </script>
</body>
</html>
